package com.heima.Serivce.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.Mapper.*;
import com.heima.Serivce.ArticleCilent;
import com.heima.Serivce.WemediamaterialNewService;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewstoArticleDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.utils.common.Tess4jUtils;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
@Transactional
@Slf4j
public class WemediaNewScan implements com.heima.Serivce.WemediaNewScan {

    @Autowired
    FileStorageService fileStorageService;

    //    Article的feign
    @Qualifier("com.heima.Serivce.ArticleCilent")
    @Autowired
    ArticleCilent articleCilent;

    @Autowired
    WemediaUserMapper wemediaUserMapper;

    @Autowired
    WemediamaterialNewMapper wemediamaterialNewMapper;

    @Autowired
    WemediaChannelMapper wemediaChannelMapper;

    @Autowired
    WmSensitiveMapper wmSensitiveMapper;



//    审核
    @Override
    @Async
    public ResponseResult NewSCan(WmNews wmNews) {
        wmNews=wemediamaterialNewMapper.selectById(wmNews.getId());
        boolean flag = false;
        boolean flag1=true;
        if(wmNews.getType()!=(short)0)
        {
//        获取文章里的文本内容和图片
            Map<String, List<String>> sth = Getsth(wmNews);
//        图片审核
            flag1= NewsImagesScan(sth.get("images"),wmNews);
        }

//        文章文本内容审核
        boolean flag2 = NewsContentScan(wmNews.getTitle() + "-" + wmNews.getContent());
//        敏感词
        boolean flag3 = NewsSensitive(wmNews.getTitle() + "-" + wmNews.getContent(),wmNews);
        flag=flag1&&flag2&&flag3;
        if (flag == true) {
//        审核成功
            wmNews.setReason("审核成功");
//        开始保存文章到App端
            ResponseResult result = SaveArticle(wmNews);

//            登记App端文章id
            if (result.getData() != null)
            wmNews.setArticleId((Long) result.getData());
            wmNews.setStatus((short) 9);
            wemediamaterialNewMapper.updateById(wmNews);
            log.info("审核成功");
            return ResponseResult.okResult("true");
        }
        else
        {
            log.error("审核失败");
//            转人工审核
//            就是把文章状态改为3
            wmNews.setStatus((short)3);
            wemediamaterialNewMapper.updateById(wmNews);
            return ResponseResult.errorResult(444,"等待人工审核");
        }
    }

    //    文章敏感词审核
    @Override
    public Boolean NewsSensitive(String Content, WmNews wmNews) {
//        获取敏感词
        List<String> mgc=GetSensitiveWord();
        SensitiveWordUtil.initMap(mgc);
//        查询文章内容是否包含敏感词
        Map<String, Integer> words = SensitiveWordUtil.matchWords(wmNews.getContent());
//        有敏感词
        if (words.size() > 0) {
            QueryWrapper<WmNews> newsQueryWrapper = new QueryWrapper<>();
            newsQueryWrapper.eq("user_id", wmNews.getUserId()).eq("title", wmNews.getTitle());
            wmNews.setStatus((short) 2);
            wmNews.setReason("出现了敏感词:" + words.keySet());
            wemediamaterialNewMapper.update(wmNews, newsQueryWrapper);
            return false;
        }
//        无敏感词
        return true;
    }

//    图片审核
    private boolean NewsImagesScan(List<String> images,WmNews wmNews) {
        boolean flag=true;
//        没有图片
        if (images.size() == 0)
            return true;

        List<byte[]> Scanimages = new ArrayList<>();
//        下载图片

        for (String image : images) {
            byte[] file = fileStorageService.downLoadFile(image);
            Scanimages.add(file);
        }
//        图片审核
//        图片敏感词审核
        List<String> Sensitives=Tess4jUtils.SensitiveWordInImage(Scanimages);
        for (String sensitive:Sensitives)
        {
            flag=NewsSensitive(sensitive,wmNews);

        }
        return flag;
    }


    //    文章内容审核
    private boolean NewsContentScan(String content) {
//        审核文章内容
        return true;
    }

    //    获取文章里的文本内容和图片
    private Map<String, List<String>> Getsth(WmNews wmNews) {
        Map<String, List<String>> content = new HashMap<>();
        List<String> textarr = new ArrayList<>();
        List<String> imagesarr = new ArrayList<>();
        List<Map> contentmapList = JSON.parseArray(wmNews.getContent(), Map.class);
        for (Map<String, Object> map : contentmapList) {
            if (map.get("type").equals("image"))
                imagesarr.add((String) map.get("value"));
            else
                textarr.add((String) map.get("value"));
        }
        content.put("text", textarr);
        content.put("images", imagesarr);
        return content;
    }

//    保存文章到App

    @GlobalTransactional
    public ResponseResult SaveArticle(WmNews wmNews) {
        //        开始保存文章到App端
        WmNewstoArticleDto wmNewstoArticleDto = new WmNewstoArticleDto();
        BeanUtils.copyProperties(wmNews, wmNewstoArticleDto);

        String name = wemediaUserMapper.selectById(wmNews.getUserId()).getName();
        wmNewstoArticleDto.setUsername(name);

        WmChannel channel = wemediaChannelMapper.selectById(wmNews.getChannelId());
        wmNewstoArticleDto.setChannelName(channel.getName());
        ResponseResult result = articleCilent.
                SaveArticle(wmNewstoArticleDto);
        return result;
    }

//    获取敏感词
    private List<String> GetSensitiveWord()
    {
 //        获取敏感词
        QueryWrapper<WmSensitive> wrapper = new QueryWrapper<>();
        List<WmSensitive> sensitives = wmSensitiveMapper.selectList(wrapper);
        List<String> mgc = sensitives.stream().map(new Function<WmSensitive, String>() {
            @Override
            public String apply(WmSensitive wmSensitive) {
                String sensitive = wmSensitive.getSensitives();
                return sensitive;
            }
        }).collect(Collectors.toList());
        return mgc;
    }


}
